<?php

namespace backend\models;

use common\helpers\FamilyTree;
use common\models\ArticleCategory;
use creocoder\nestedsets\NestedSetsBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;

class Category extends ArticleCategory
{
    public $parent_id;

    /** 为model添加相应的行为，这里的这个写法按设计模式应该升级，分层代码结构，面向切面编程进行 @TODO 代码分层问题
     * @Notes
     * @Interface behaviors
     *
     *
     * @return array
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-23 0:14
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            [
                'class' => NestedSetsBehavior::className(),
                'treeAttribute' => 'tree',
            ],
        ];
    }

    /**
     * @Notes
     * @Interface rules
     *
     *
     * @return array
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2020-01-11 23:51
     */
    public function rules()
    {
        return ArrayHelper::merge(
            parent::rules(),
            [
                [['parent_id'], 'integer'],
                [['parent_id', 'sort'], 'default', 'value' => 0],
            ]
        );
    }

    /**
     * @Notes
     * @Interface attributeLabels
     *
     *
     * @return array
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2020-01-11 23:51
     */
    public function attributeLabels()
    {
        return ArrayHelper::merge(
            parent::attributeLabels(),
            [
                'parent_id' => Yii::t('app', 'Parent Category Id'),
            ]
        );
    }

    /**
     * @Notes   覆盖default 的验证规则，设置验证规则
     * @Interface scenarios
     *
     * @return array
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-23 2:48
     */
    public function scenarios()
    {
        return array_merge(
            parent::scenarios(),
            [
                'default' => [
                    'parent_id',
                    'tree',
                    'name',
                    'alias',
                    'sort',
                    'remark',
                ],
            ]
        );
    }

    /**
     * @Notes  重写find方法，重载分类NestedSetsQueryBehavior 方法
     * @Interface find
     *
     *
     * @return CategoryQuery|\common\models\ArticleCategoryQuery
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-23 2:40
     */
    public static function find()
    {
        return new CategoryQuery(get_called_class());
    }

    /**
     * @Notes  制造parent_id 方便有些地方使用，其实可以废弃 此方法只在 toArray()后有效 注意asArray()查询后无效，需要循环处理
     * @Interface fields
     *
     * @return array|false
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-23 0:12
     */
    public function fields()
    {
        $fields = parent::fields();
        $fields['parent_id'] = function ($model) {
            $parent = $model->parents(1)->one();
            if (!empty($parent)) {
                return $model->parents(1)->one()['id'];
            } else {
                return null;
            }
        };

        return $fields;
    }

    /**
     * @Notes  生产分类列表
     * @Interface getCategoriesName
     *
     * @return array
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-23 0:15
     */
    public static function getCategoriesName()
    {
        $categories = self::getCategories();
        $data = [];
        foreach ($categories as $k => $category) {
            if (isset($categories[$k + 1]['level']) && $categories[$k + 1]['level'] == $category['level']) {
                $name = ' ├' . $category['name'];
            } else {
                $name = ' └' . $category['name'];
            }
            if (end($categories) == $category) {
                $sign = ' └';
            } else {
                $sign = ' │';
            }
            $data[$category['id']] = str_repeat($sign, $category['level'] - 1) . $name;
        }

        return $data;
    }

    /**
     * @Notes  递归生成符合前端条件的树状数据结构
     * @Interface getCategories
     *
     * @return array
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-23 0:16
     */
    public static function getCategories()
    {
        $Categorys = self::find()->all(); //所有分类
        $array = [];
        foreach ($Categorys as $key => $Category) {
            $array[$key] = $Category->toArray();
        }
        $familyTree = new FamilyTree($array);
        $array = $familyTree->getDescendants(0);

        return ArrayHelper::index($array, 'id');
    }
}
